package leetcode.Y2024M7;

/**
 * S208实现前缀树
 */
public class Trie {
    // 创建一个26叉树
    class TrieTree {
        private boolean end;
        TrieTree[] next;

        public TrieTree() {
            end = false;
            next = new TrieTree[26];
        }
    }

    private TrieTree root;

    public Trie() {
        root = new TrieTree();
    }

    public void insert(String word) {
        TrieTree node = root;
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (node.next[index] == null) {
                node.next[index] = new TrieTree();
            }
            node = node.next[index];
        }
        node.end = true;
    }

    public boolean search(String word) {
        TrieTree node = root;
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (node.next[index] == null) return false;
            node = node.next[index];
        }
        return node.end;
    }

    public boolean startsWith(String prefix) {
        TrieTree node = root;
        for (char c : prefix.toCharArray()) {
            int index = c - 'a';
            if (node.next[index] == null) return false;
            node = node.next[index];
        }
        return true;
    }
}
